package serveur;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

import remote.ClientInterface;
import remote.PrivateInterface;
import remote.PublicInterface;
import remote.Tweet;
import serveur.exception.NotExistException;

public class PrivateServer extends UnicastRemoteObject implements PrivateInterface {

	private User user;
	private ServerDatas datas;

	protected PrivateServer(User u, ClientInterface ci) throws RemoteException {
		// Connexion s��curis�� par ssl
		super(0, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory());
		datas = ServerDatas.getInstance();
		user = u;
		// Set user to connected
		datas.connected.put(user.getPseudo(), ci);
		// If has non read message then send message to clients
		if (!u.getPending().isEmpty())
			ci.messagePending();
	}

	@Override
	public void deconnexion() throws RemoteException {
		// Set user to unconnected
		datas.connected.remove(user.getPseudo());
		
	}

	@Override
	public void tweeter(Tweet t) throws RemoteException {
		t.setAuthor(user.getPseudo());
		// Add tweet to the recent list
		datas.addTweet(t);
		List<String> followers = user.getFollowers();
		ClientInterface ci = null;
		for (String pseudo : followers) {
			// If user is connected
			if ((ci = datas.connected.get(pseudo)) != null)
				ci.messagePending();

			try {
				// Add tweet in user's pending messages
				datas.getUser(pseudo).getPending().add(t);
			} catch (NotExistException e) {
				// If user can't be found we remove him
				user.removeFollowers(pseudo);
			}
		}
		datas.serialize();
	}

	@Override
	public void follow(String pseudo) throws RemoteException {
		try {
			// If user can be found we add follower
			User u = datas.getUser(pseudo);
			u.addFollowers(user.getPseudo());
			// Then we add follow
			user.addFollow(pseudo);
		} catch (NotExistException e) {
			// Else we do nothing
		}
	}

	public List<Tweet> getPendingMessage() throws RemoteException {
		List<Tweet> res = new ArrayList<Tweet>(user.getPending());
		user.getPending().clear();
		return res;
	}

	public List<String> getUsers() throws RemoteException {
		List<String> res = datas.getUsers();
		// Remove current user
		res.remove(user.getPseudo());
		return res;
	}
}
